<template>
    <div class="promotion-info">
        <div class="component-title">
            <h3>商品促销信息</h3>
        </div>

        <el-form :model="form" label-width="120px" ref="promotionForm">
            <!-- 标签部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-price-tag"></i>
                    <span>商品标签</span>
                </div>

                <el-form-item label="商品标签" prop="tags">
                    <el-select v-model="form.tags" multiple placeholder="请选择标签" @change="onTagsChange">
                        <el-option v-for="item in tagOptions" :key="item.id" :label="item.name" :value="item.id">
                            <span :style="{ color: item.style_config && item.style_config.color }">{{ item.name
                                }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>

                <div class="tag-preview" v-if="form.tags.length > 0">
                    <div class="preview-title">标签预览</div>
                    <div class="tag-list">
                        <div v-for="tagId in form.tags" :key="tagId" class="tag-item" :style="getTagStyle(tagId)">
                            {{ getTagName(tagId) }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 促销活动部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-shopping-cart-full"></i>
                    <span>促销活动</span>
                </div>

                <el-form-item label="促销活动" prop="promotions">
                    <el-select v-model="form.promotions" multiple placeholder="请选择促销活动" @change="onPromotionsChange">
                        <el-option v-for="item in promotionOptions" :key="item.id" :label="item.name" :value="item.id">
                            <div class="promotion-option">
                                <span>{{ item.name }}</span>
                                <span class="promotion-desc">
                                    {{ getPromotionDesc(item) }}
                                </span>
                            </div>
                        </el-option>
                    </el-select>
                </el-form-item>

                <div class="promotion-preview" v-if="form.promotions.length > 0">
                    <div class="preview-title">已选促销活动</div>
                    <el-table :data="selectedPromotions" border size="small" style="width: 100%">
                        <el-table-column prop="name" label="活动名称" width="180"></el-table-column>
                        <el-table-column label="促销类型" width="120">
                            <template slot-scope="scope">
                                {{ getPromotionTypeText(scope.row.type) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="优惠内容">
                            <template slot-scope="scope">
                                {{ getPromotionDesc(scope.row) }}
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <!-- 预售设置部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-time"></i>
                    <span>预售设置</span>
                </div>

                <el-form-item label="开启预售" prop="is_presell">
                    <el-switch v-model="form.presell_config.is_presell" @change="onPresellChange"></el-switch>
                </el-form-item>

                <template v-if="form.presell_config.is_presell">
                    <el-form-item label="预售开始时间" prop="presell_start_time">
                        <el-date-picker v-model="form.presell_config.start_time" type="datetime" placeholder="选择预售开始时间"
                            @change="onPresellTimeChange"></el-date-picker>
                    </el-form-item>

                    <el-form-item label="预售结束时间" prop="presell_end_time">
                        <el-date-picker v-model="form.presell_config.end_time" type="datetime" placeholder="选择预售结束时间"
                            @change="onPresellTimeChange"></el-date-picker>
                    </el-form-item>

                    <el-form-item label="发货天数" prop="delivery_days">
                        <el-input-number v-model="form.presell_config.delivery_days" :min="1" :max="30"
                            placeholder="预售结束后多少天发货" @change="onPresellDaysChange"></el-input-number>
                        <span class="form-tip">预售结束后多少天发货</span>
                    </el-form-item>
                </template>
            </div>

            <!-- 优先购买权部分 -->
            <div class="form-section">
                <div class="section-title">
                    <i class="el-icon-user"></i>
                    <span>优先购买权</span>
                </div>

                <el-form-item label="会员优先" prop="member_priority">
                    <el-switch v-model="form.member_priority" @change="onMemberPriorityChange"></el-switch>
                    <span class="form-tip">开启后，会员可优先购买该商品</span>
                </el-form-item>

                <el-form-item label="限购数量" prop="limit_per_member">
                    <el-input-number v-model="form.limit_per_member" :min="0" :max="999" placeholder="0表示不限制"
                        @change="onLimitChange"></el-input-number>
                    <span class="form-tip">每个会员限购数量，0表示不限制</span>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
import { debounce } from 'lodash-es';

export default {
    name: 'PromotionInfo',
    props: {
        formData: {
            type: Object,
            required: true
        },
        tagOptions: {
            type: Array,
            default: () => []
        },
        promotionOptions: {
            type: Array,
            default: () => []
        }
    },
    data() {
        // 确保表单数据结构完整
        const defaultForm = {
            tags: [],
            promotions: [],
            presell_config: {
                is_presell: false,
                start_time: null,
                end_time: null,
                delivery_days: 7
            },
            member_priority: false,
            limit_per_member: 0
        };

        return {
            form: {
                ...defaultForm,
                ...this.formData
            }
        };
    },
    computed: {
        selectedPromotions() {
            return this.promotionOptions.filter(item => this.form.promotions.includes(item.id));
        }
    },
    watch: {
        formData: {
            handler(val) {
                // 避免不必要的深层更新
                const needUpdate = JSON.stringify(this.form) !== JSON.stringify(val);
                if (needUpdate) {
                    this.form = {
                        ...val,
                        member_priority: val.member_priority !== undefined ? val.member_priority : this.form.member_priority,
                        limit_per_member: val.limit_per_member !== undefined ? val.limit_per_member : this.form.limit_per_member
                    };
                }
            },
            deep: true
        },
        'form.tags': function (val) {
            // 仅当标签变化时更新
            this.debouncedEmit(this.form);
        },
        'form.promotions': function (val) {
            // 仅当促销活动变化时更新
            this.debouncedEmit(this.form);
        }
    },
    created() {
        // 创建防抖函数
        this.debouncedEmit = debounce(this.emitUpdate, 300);
    },
    methods: {
        emitUpdate(val) {
            this.$emit('update-form', val);
        },
        getTagStyle(tagId) {
            const tag = this.tagOptions.find(item => item.id === tagId);
            if (tag && tag.style_config) {
                return {
                    backgroundColor: tag.style_config.color ? `${tag.style_config.color}20` : '#f0f0f0',
                    color: tag.style_config.color || '#333',
                    borderColor: tag.style_config.color ? `${tag.style_config.color}50` : '#ddd'
                };
            }
            return {};
        },
        getTagName(tagId) {
            const tag = this.tagOptions.find(item => item.id === tagId);
            return tag ? tag.name : '';
        },
        getPromotionTypeText(type) {
            const typeMap = {
                1: '折扣',
                2: '减价',
                3: '固定价',
                4: '赠品',
                5: '满减'
            };
            return typeMap[type] || '未知';
        },
        getPromotionDesc(promotion) {
            switch (promotion.type) {
                case 1:
                    return `打${promotion.discount_value}折`;
                case 2:
                    return `立减${promotion.discount_value}元`;
                case 3:
                    return `固定价${promotion.discount_value}元`;
                case 4:
                    return '赠送赠品';
                case 5:
                    return `满${promotion.threshold_value}减${promotion.discount_value}元`;
                default:
                    return '';
            }
        },
        validate() {
            return new Promise((resolve, reject) => {
                if (!this.$refs.promotionForm) {
                    reject(new Error('促销表单组件未正确加载'));
                    return;
                }

                this.$refs.promotionForm.validate(valid => {
                    if (valid) {
                        // 额外的业务逻辑验证
                        if (this.form.presell_config && this.form.presell_config.is_presell) {
                            // 验证预售时间
                            if (this.form.presell_config.start_time && this.form.presell_config.end_time) {
                                if (this.form.presell_config.start_time >= this.form.presell_config.end_time) {
                                    reject(new Error('预售结束时间必须晚于开始时间'));
                                    return;
                                }
                            } else if (!this.form.presell_config.start_time) {
                                reject(new Error('请选择预售开始时间'));
                                return;
                            } else if (!this.form.presell_config.end_time) {
                                reject(new Error('请选择预售结束时间'));
                                return;
                            }
                        }
                        resolve();
                    } else {
                        reject(new Error('促销信息验证失败'));
                    }
                });
            });
        },
        onTagsChange() {
            this.debouncedEmit(this.form);
        },
        onPromotionsChange() {
            this.debouncedEmit(this.form);
        },
        onPresellChange() {
            this.debouncedEmit(this.form);
        },
        onPresellTimeChange() {
            this.debouncedEmit(this.form);
        },
        onPresellDaysChange() {
            this.debouncedEmit(this.form);
        },
        onMemberPriorityChange() {
            this.debouncedEmit(this.form);
        },
        onLimitChange() {
            this.debouncedEmit(this.form);
        }
    }
};
</script>

<style scoped>
.promotion-info {
    padding: 20px;
}

.component-title {
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.component-title h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.form-section {
    margin-bottom: 30px;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 4px;
}

.section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.section-title i {
    margin-right: 8px;
    color: #409EFF;
}

.form-tip {
    margin-left: 10px;
    color: #999;
    font-size: 12px;
}

.preview-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
    margin-top: 15px;
}

.tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.tag-item {
    padding: 4px 12px;
    border-radius: 4px;
    font-size: 12px;
    border: 1px solid #ddd;
    background: #f0f0f0;
}

.promotion-option {
    display: flex;
    justify-content: space-between;
    width: 100%;
}

.promotion-desc {
    color: #ff6b00;
    font-size: 12px;
}

.promotion-preview {
    margin-top: 15px;
}
</style>